import hasOwnProp from './hasOwnProp';

/**
 * @description: 深度获取对象属性值
 * @param {object} obj 任意可迭代对象
 * @param {String} path 对象属性字符串
 * @param {*} defaultValue 找不到对应属性默认返回
 * @return {*}
 * @example: getPropByPath([{name:1}],'[0].name')
 */
export default function getPropByPath(obj, path, defaultValue = '') {
  if (obj && path) {
    let value = obj;
    const keyArr = path.replace(/\[(\w+)\]/g, '.$1').replace(/^\./, '').split('.');
    for (let i = 0, len = keyArr.length; i < len; i++) {
      const key = keyArr[i];
      if (value && hasOwnProp(value, key)) {
        value = value[key];
      } else {
        return defaultValue;
      }
    }
    return value;
  }
  return defaultValue;
}
